package cn.lg.soar.system.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.auth.entity.MenuPermit;
import cn.lg.soar.system.auth.mapper.MenuPermitMapper;
import cn.lg.soar.system.config.AuthCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class MenuPermitService extends ServiceImpl<MenuPermitMapper, MenuPermit> {

    /**
     * 根据菜单id获取权限
     * @param menuId
     * @return
     */
    @Cacheable(value = AuthCacheKey.PERMIT_ID_BY_MENU, key = "#menuId", cacheManager = "remote")
    public List<Long> getPermitIds(Long menuId) {
        return listObjs(
                Wrappers.<MenuPermit>lambdaQuery()
                        .select(MenuPermit::getPermitId)
                        .eq(MenuPermit::getMenuId, menuId),
                x -> Long.parseLong(x.toString())
        );
    }

    /**
     * 设置菜单权限
     * @param menuId
     * @param permits
     */
    @Caching(evict = {
            @CacheEvict(value = AuthCacheKey.PERMIT_ID_BY_MENU, key = "#menuId", cacheManager = "remote"),
            @CacheEvict(value = AuthCacheKey.PERMIT_CODE_BY_ROLE, allEntries = true)
    })
    @Transactional(rollbackFor = RuntimeException.class)
    public void setMenuPermit(Long menuId, Collection<Long> permitIds) {
        // 清空旧值
        clearByMenu(menuId);
        // 批量保存新值
        if (CollectionUtils.isEmpty(permitIds)) {
            return;
        }
        List<MenuPermit> collect = permitIds.stream()
                .distinct()
                .map(x -> {
                    MenuPermit data = new MenuPermit();
                    data.setMenuId(menuId);
                    data.setPermitId(x);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存菜单权限失败");
    }

    @Caching(evict = {
            @CacheEvict(value = AuthCacheKey.PERMIT_ID_BY_MENU, key = "#menuId", cacheManager = "remote"),
            @CacheEvict(value = AuthCacheKey.PERMIT_CODE_BY_ROLE, allEntries = true)
    })
    public void clearByMenu(Long menuId) {
        this.remove(Wrappers.<MenuPermit>lambdaQuery().eq(MenuPermit::getMenuId, menuId));
    }

    public void clearByPermit(Long permitId) {
        this.remove(Wrappers.<MenuPermit>lambdaQuery().eq(MenuPermit::getPermitId, permitId));
    }
}
